<!--  -->
<template>
  <div class="myadmin-shoplist">
    <top-header></top-header>
    <div class="myadmin-shoplist-table">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline>
              <el-form-item label="评分">
                <span>{{ props.row.rating }}</span>
              </el-form-item>
              <el-form-item label="最近的评价的人数">
                <span>{{ props.row.rating_count }}</span>
              </el-form-item>
              <el-form-item label="最近订单数量">
                <span>{{ props.row.recent_order_num }}</span>
              </el-form-item>
              <el-form-item label="店铺id">
                <span>{{ props.row.id }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="店铺名称" prop="name"> </el-table-column>
        <el-table-column label="店铺logo" prop="image_path">
            <template slot-scope="scope">
          <el-image :src="baseImgPath+scope.row.image_path" style="width:200px;height:200px"></el-image>
        </template>
        </el-table-column>
        <el-table-column label="店铺地址" prop="address"> </el-table-column>
        <el-table-column label="店铺介绍" prop="description"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button  @click="handleEdit(scope)">编辑</el-button>
             <el-button  @click="handleAdd(scope)">添加食品</el-button>
            <el-button  type="danger" @click="handleDelete(scope.$index,scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog title="修改店铺信息" :visible.sync="dialogVisible" width="50%">
      <el-form
        :rules="rules"
        :model="form"
        ref="form"
        label-width="80px"
        :inline="false"
        size="normal"
      >
        <el-form-item label="店铺名称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <!-- @select="handleSelect" -->
          <el-autocomplete
            :fetch-suggestions="querySearch"
            class="inline-input"
            v-model="form.address"
            placeholder="请输入内容"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="店铺介绍" prop="description">
           <el-input v-model="form.description" placeholder="请输入内容" size="normal" clearable ></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
           <el-input v-model="form.phone" placeholder="请输入内容" size="normal" clearable ></el-input>
        </el-form-item>
        <el-form-item label="上传图片" >
            <el-upload
                class="avatar-uploader"
                :action="BASE_URL+'v1/addimg/avatar'"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="selectTable.image_path" :src="baseImgPath + selectTable.image_path" class="avatar">
                <i v-else class="el-icon-plusavatar-uploader-icon"></i>
            </el-upload>
        </el-form-item>
        <el-form-item label="上传店铺营业执照" size="normal">
            <el-upload
                :action="BASE_URL+'v1/addimg/avatar'"
                class="avatar-uploader"
                 :show-file-list="false"
                :on-success="handleBusinessUpload"
                :before-upload="beforeAvatarUpload">
                <el-image :src="baseImgPath + selectTable.image_path" fit="fill" :lazy="true" v-if="businessLicenseUrl"></el-image>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-form-item>
        <el-form-item label="食品分类" size="normal">
            <el-cascader
                v-model="cascaderValue"
                :options="options"
                @change="handleChange"></el-cascader>
        </el-form-item>
        
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit('form')"
          >确 定</el-button
        >
        
      </span>
    </el-dialog>
    
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import TopHeader from "./top-header";
import { getShoplist, searchPlace,getFoodCategory,updateShop,deleteResturant } from "@/api/api";
import {BASE_URL,baseImgPath} from "@/config/env"
export default {

  //import引入的组件需要注入到对象中才能使用
  components: {
    "top-header": TopHeader,
  },
  data() {
    //这里存放数据
    return {
    
      rules:{
        name:[{required:true,message:"请输入店铺名称",trigger:"blur"}],
        address:[{required:true,message:"请输入地址",trigger:"blur"}],
        description:[{required:true,message:"请输入店铺介绍",trigger:"blur"}],
        phone:[{required:true,message:"请输入电话",trigger:"blur"}],
      },
      form: {}, // 弹出表格信息
      dialogVisible: false, // 弹出窗口显示或者隐藏
      tableData: [],
      suggestion: "", // 下拉框建议值
      BASE_URL:BASE_URL,
      baseImgPath:baseImgPath,
      imageUrl:"",
      businessLicenseUrl:"",
      cascaderValue:["快餐便当","简餐"],
      options:[],
      selectTable: {},
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
     //提交验证
     handleSubmit:function(form){
         this.$refs[form].validate(async (valid)=>{
             if(valid){
                 this.$message("准备提交表单");
                 //向后台提交数据
                 let {id,name,address,description,phone,image_path} = this.form;
                //  console.log(this.form);
                 //食品种类
                // console.log(this.cascaderValue);
                this.selectTable.category = this.cascaderValue.join("/");
                console.log("selectTable",this.selectTable);
                // const res = await updateShop(this.selectTable);
                // console.log("res",res);
                let category = this.selectTable.category
                // console.log(category);
                let result = await updateShop({
                    category,
                    id,
                    name,
                    address,
                    description,
                    phone,
                    image_path,
                });
                if(result.status === 1){
                    this.dialogVisible = false;
                    this.$message({
                        type:"success",
                        message:"更新成功"
                    });
                }
             }else{
                 this.$message({
                     type:"error",
                     message:"表单有误，请检查"
                 })
             }
         })
     },
 
     createOptions:function(foodCategory){
         let options = [];
         foodCategory.map((res,index)=>{
             options.push({
                 value:res.name,
                 label:res.name,
                 children:[],
             });
             //子菜单
             if(res.sub_categories.length > 0){
                 res.sub_categories.map((subItem,subIndex)=>{
                     options[index].children.push({
                         value:subItem.name,
                         label:subItem.name
                     })
                 })
             }
         });
         this.options = options;
     },
     //级联菜单发生变化的时候的回调函数
     handleChange:function(){

     },
     //上传营业执照
     handleBusinessUpload(res,file){
         this.businessLicenseUrl = baseImgPath + res.image_path;
     },
     //上传成功的钩子
     handleAvatarSuccess(res){
          if (res.status == 1) {
        this.selectTable.image_path = res.image_path;
      } else {
        this.$message.error("上传图片失败！");
      }
     },
     //上传之前的钩子
     beforeAvatarUpload(file){
         const isLt2M = file.size/1024/1024<2;
         if(!isLt2M){
             this.$message.error("上传图片大小不能超过2M")
         }
         return isLt2M
     },
    
     querySearch(queryString, cb) {
        // 如果空的话 传到后台会报错
     let timeId = setTimeout(async function(){
          if(!queryString){
          cb([]);
          return false;
      }
      let res = await searchPlace({
        keyword: queryString,
      });
      let filterResult = res.map((v)=>{
          return {
              value:v.address
          }
      })
      console.log(filterResult)
    //   console.log(res);
      cb(filterResult);
     },500)
    },
   handleEdit: function (scope) {
      // 显示弹出窗口
      // scope.row => 一行的信息
      this.dialogVisible = true;
      this.form = scope.row;
      this.selectTable = scope.row;
      this.imageUrl = baseImgPath+scope.row.image_path;
      console.log(scope);

    },
    handleDelete:async function(index,scope){
        const result = await deleteResturant({
            restaurant_id:scope.row.id
        });
        if(result.status===1){
            this.$message({
                type:"success",
                message:"删除成功",
            })
            this.tableData.splice(index,1);
        }else{
            this.$message({
                type:"error",
                message:"删除失败"
            })
        }
    },
   
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  async created() {
    let res = await getShoplist();
    let foodCategory = await getFoodCategory();
    this.createOptions(foodCategory);
    this.tableData = res;
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='less' scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>